package com.nxy.cpfsfe.busi.btmgtsk;

import com.adtec.starring.datapool.CompSDO;
import com.adtec.starring.datapool.EPOper;
import com.adtec.starring.exception.BaseException;
import com.adtec.starring.struct.dta.DtaInfo;
import com.adtec.starring.util.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nxy.cpfsfe.busi.btmgtsk.endd.NCSEndDChkASrv;
import com.nxy.cpfsfe.enumtype.RespCd;
import com.nxy.cpfsfe.mybatis.mapper.TrChlBizTypMapper;
import com.nxy.cpfsfe.mybatis.mapper.TrSysBizTypMapper;
import com.nxy.cpfsfe.mybatis.pojo.TrSysBizTyp;
import com.nxy.cpfsfe.util.DateUtil;
import com.nxy.cpfsfe.util.LogUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class BTmgWebSrvBean {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(BTmgWebSrvBean.class);
	
	/**
	 * 
	 * Description:统一接收内管系统发送来的请求，根据initrSeqno中带的方法名
	 * 			     调用对应方法进行处理
	 *
	 * @author jjw
	 * @data 2019年9月18日
	 */
	public void unifySrv(){
		
		try{
			String tpId = DtaInfo.getInstance().getTpId();
			String initrSeqno = (String) EPOper.get(tpId, "ReqBean[0].head[0].initrSeqno");
			String bizMsg = (String)EPOper.get(tpId, "ReqBean[0].body[0].BizMsg");
			MDC.put("ROUTINGKEY" , LogUtil.getLogFileName("MGR", StringUtils.isNotBlank(initrSeqno) ? initrSeqno : "unknown"));
			if(initrSeqno == null){
				throw new BaseException(RespCd.NCPO0110,"报文体缺少initrSeqno属性");
			}
			if(bizMsg == null){
				throw new BaseException(RespCd.NCPO0110,"报文体缺少BizMsg属性");
			}
			LOGGER.info("内管调用定时类Web统一处理模块[{}]，请求体：[{}]",initrSeqno,bizMsg);
			
			Method method = this.getClass().getDeclaredMethod(initrSeqno,String.class);
			method.setAccessible(true);
			method.invoke(this,bizMsg);
			
			LOGGER.info("内管调用定时类Web统一处理模块[{}]成功",initrSeqno);
		}catch(BaseException e){
			//业务异常处理
			String tpId = DtaInfo.getInstance().getTpId();
            EPOper.put(tpId, "RspBean[0].head[0].rspsCd", e.getErrorCode());
            EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", e.getErrorDesc());
            CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
            respBody.setValue("BizMsg", "F");
            
            //异常日志记录
            String errorMsg = String.format("内管调用定时类Web统一处理模块失败，错误码:%s,错误信息:%s",e.getErrorCode(),e.getErrorDesc());
            LOGGER.error(errorMsg,e);
		}catch(InvocationTargetException e){
			Throwable tarEx = e.getTargetException();
			
			if(tarEx instanceof BaseException){
				//业务异常
				String tpId = DtaInfo.getInstance().getTpId();
	            EPOper.put(tpId, "RspBean[0].head[0].rspsCd", ((BaseException)tarEx).getErrorCode());
	            EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", ((BaseException)tarEx).getErrorDesc());
	            CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
	            respBody.setValue("BizMsg", "F");
	            
	            String errorMsg = String.format("内管调用定时类Web统一处理模块失败，错误码:%s,错误信息:%s",((BaseException)tarEx).getErrorCode(),((BaseException)tarEx).getErrorDesc());
	            LOGGER.error(errorMsg,tarEx);
			}else{
				//未知异常
				String tpId = DtaInfo.getInstance().getTpId();
	            EPOper.put(tpId, "RspBean[0].head[0].rspsCd", "90000");
	            EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "未知异常");
	            CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
	            respBody.setValue("BizMsg", "F");
	            
	            LOGGER.error("内管调用定时类Web统一处理模块失败，发生未知异常",tarEx);
			}
		}catch(Throwable e){
			//未知异常日志记录
            String tpId = DtaInfo.getInstance().getTpId();
            EPOper.put(tpId, "RspBean[0].head[0].rspsCd", "90000");
            EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "未知异常");
            CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
            respBody.setValue("BizMsg", "F");
            
            LOGGER.error("内管调用定时类Web统一处理模块失败，发生未知异常",e);
		}finally {
			try{
				MDC.clear();
				//资源对象释放
			}catch (Exception e){
				//异常日志记录
				String errorMsg = "释放MDC资源异常";
				LOGGER.error(errorMsg,e);
			}
		}
		
	}
	
	/**
	 * 
	 * Description:业务系统日终对账文件生成
	 *
	 * @author jjw
	 * @data 2019年9月21日
	 */
	private void doBizEndDChkA(String bizMsg){
		
		SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");
		
		JSONObject reqBody = null;
		try{
			reqBody = JSON.parseObject(bizMsg);
		}catch(Exception e){
			throw new BaseException(RespCd.NCPO0101,e,"报文体BizMsg属性值解析失败");
		}
		
		String bizSysId = reqBody.getString("bizSysId");
		String chkAD = reqBody.getString("chkAD");
		
		TrSysBizTypMapper trSysBizTypMapper = sqlSession.getMapper(TrSysBizTypMapper.class);
		TrChlBizTypMapper trChlBizTypMapper = sqlSession.getMapper(TrChlBizTypMapper.class);
		List<TrSysBizTyp> trSysBizTyps = trSysBizTypMapper.queryOrgIdByBizSysId(bizSysId);
		if(trSysBizTyps != null && trSysBizTyps.size() > 0){
			List<String> pCIds = trChlBizTypMapper.queryOpenChlByOrgId(trSysBizTyps);
			if(pCIds != null && pCIds.size() > 0){
				try{
					for(String pCId : pCIds){
						if("NCS".equals(pCId)){
							new NCSEndDChkASrv(bizSysId,pCId,DateUtil.str2Date(chkAD,"yyyyMMdd"),"BTmg").endDChkAProcess();
						}else{
							String errMsg = String.format("当前系统不支持[%s]通道的对账文件生成",pCId);
							throw new BaseException(RespCd.NCPS2001,errMsg);
						}
					}
				}catch (BaseException e){
					if(e.getErrorCode().equals(RespCd.NCPO0001) || e.getErrorCode().equals(RespCd.NCPO6410)){
						LOGGER.warn(e.getErrorDesc());
						String tpId = DtaInfo.getInstance().getTpId();
						EPOper.put(tpId, "RspBean[0].head[0].rspsCd", e.getErrorCode());
						EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", e.getErrorDesc());
						CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
						respBody.setValue("BizMsg", "F");
						return;
					}else{
						throw e;
					}
				}
			}else{
				String errMsg = String.format("业务系统[%s]的机构未开通任何通道，无法产生对账文件",bizSysId);
				throw new BaseException(RespCd.NCPO6804,errMsg);
			}
		}else{
			String errMsg = String.format("业务系统[%s]未配置任何机构，无法产生对账文件",bizSysId);
			throw new BaseException(RespCd.NCPO6804,errMsg);
		}
		
		String tpId = DtaInfo.getInstance().getTpId();
		EPOper.put(tpId, "RspBean[0].head[0].rspsCd", RespCd.NCPI0000);
		EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "处理成功");
		CompSDO respBody = EPOper.getCompSDO(tpId, "RspBody");
		respBody.setValue("BizMsg", "S");
		
	}

}
